package com.sgj.controller;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.sgj.entity.User;
import com.sgj.service.UserService;
import com.sgj.utils.JWTUtils;
import com.sgj.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-12-16
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public LoginVo login(@RequestBody User user) {
        log.info("[UserController][login] 用户名:[{}], 密码:[{}]", user.getUsername(), user.getPassword());

        try {
            User login = userService.login(user);
            // 生成 JWT token
            String token = JWTUtils.getToken(login);
            return LoginVo.builder()
                    .state(true)
                    .msg("登录成功")
                    .token(token)
                    .build();
        } catch (Exception e) {
            return  LoginVo.builder()
                    .state(false)
                    .msg("登录失败")
                    .build();
        }
    }

    @GetMapping("/test")
    public LoginVo test() {
        return LoginVo.builder()
                .state(true)
                .msg("验证成功")
                .build();
    }

}